package com.itcanteen.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itcanteen.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author baimugudu
 * @email 2415621370@qq.com
 * @date 2022/10/24 10:11
 */
@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter  implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        //1.  由于request对象需要使用到子类特有的方法，所以强制类型转换
        HttpServletRequest httpServletRequest =  (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse =  (HttpServletResponse) servletResponse;

        //获取本次请求的url
        String requestURI = httpServletRequest.getRequestURI();

        StringBuffer requestURL = httpServletRequest.getRequestURL();
        log.info("this is url:{}",requestURL.toString());

        log.info("this is uri：{}",requestURI);

        //3. 定义一个数组存储需要放行的url，判断本次请求是否需要登录权限的。
        String[] urls = {"/backend/**","/front/**","/employee/login","/common/**"};

        boolean b = checkUrl(urls, requestURI);
        if(b){
            //直接放行
            log.info("验证通过，不需要登录，直接访问");
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return ;
        }

        HttpSession session = httpServletRequest.getSession();
        if(session.getAttribute("user")!=null){
           // 如果用户已经登录，也可以直接放行
            log.info("用户是登陆状态，直接放行");
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return ;
        }

        //5. 如果没有登录，返回数据前端，让前端发生跳转
        /*
          目前你使用的是Filter，不是springmvc ，所有如果你需要返回json数据，需要自己转换，

         */
        log.info("用户用户去登陆才能访问---");
        String notloginJson = JSON.toJSONString(R.error("NOTLOGIN"));
        httpServletResponse.getWriter().print(notloginJson);


    }

    //该类专门用于匹配请求路径的。
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    private boolean checkUrl(String[] urls,String requestUrl){
        //遍历所有放行的路径，是否与本次请求的路径匹配
        for(String url:urls){
            if(antPathMatcher.match(url,requestUrl)){
                return true;
            }
        }

        return false;
    }
}
